const User = require("../models/user");
const jwt = require("jsonwebtoken");
const secret = process.env.SECRET;

class Users {
  async find(ctx) {
    ctx.body = await User.find();
  }

  async findById(ctx) {
    const { fields } = ctx.query;
    // const selectFields = fields
    //   .split(";")
    //   .filter(f => f)
    //   .map(f => " +" + f)
    //   .join("");
    const res = await User.findById(ctx.params.id); //.select(selectFields);
    if (!res) {
      ctx.throw(404, "用户不存在！");
    }
    ctx.body = res;
  }

  async create(ctx) {
    ctx.verifyParams({
      name: { type: "string", required: true },
      password: { type: "string", required: true },
      age: { type: "number", required: false }
    });
    const { name } = ctx.request.body;
    const reuser = await User.findOne({ name });
    if (reuser) {
      ctx.throw(409, "用户名已经占用");
    }
    const user = await new User(ctx.request.body).save();
    ctx.body = user;
  }

  async update(ctx) {
    ctx.verifyParams({
      name: { type: "string", required: false },
      password: { type: "string", required: false },
      age: { type: "number", required: false },
      avatar_url: { type: "string", required: false },
      gender: { type: "string", required: false },
      slug: { type: "string", required: false },
      locations: { type: "array", itemType: "string", required: false },
      business: { type: "string", required: false },
      employments: { type: "array", itemType: "object", required: false },
      educations: { type: "array", itemType: "object", required: false }
    });
    const user = await User.findOneAndUpdate(
      { _id: ctx.params.id },
      ctx.request.body,
      {
        new: true
      }
    );
    if (!user) {
      ctx.throw(404, "更新的用户不存在");
    }
    ctx.body = user;
  }

  async del(ctx) {
    const user = await User.findByIdAndRemove(ctx.params.id);
    if (!user) {
      ctx.throw(404, "要删除的用户不存在");
    }
    ctx.status = 204;
  }

  authMe(ctx) {
    jwt.verify(ctx.params.token, secret, (err, decode) => {
      if (err) {
        ctx.throw(401);
      }
      ctx.body = {
        // 感觉不用提供用户名撩
        // name: decode.name,
        _id: decode._id
      };
    });
  }
}

// 导出时即完成实例化
module.exports = new Users();
